'use strict';

const Controller = require('egg').Controller;

class ReviewsController extends Controller {
  // 获取房源评价列表
  async list() {
    const { ctx } = this;
    const { propertyId } = ctx.params;
    const { page, pageSize } = ctx.query;

    try {
      const data = await ctx.service.review.list(propertyId, { page, pageSize });
      ctx.body = { success: true, data };
    } catch (e) {
      ctx.status = 500;
      ctx.body = { success: false, message: '获取评价列表失败' };
    }
  }

  // 获取房源评价统计
  async stats() {
    const { ctx } = this;
    const { propertyId } = ctx.params;

    try {
      const data = await ctx.service.review.getStats(propertyId);
      ctx.body = { success: true, data };
    } catch (e) {
      ctx.status = 500;
      ctx.body = { success: false, message: '获取评价统计失败' };
    }
  }

  // 创建评价
  async create() {
    const { ctx } = this;
    const { property_id, rating, content, images } = ctx.request.body;
    const user_id = ctx.state.user?.id; // 从认证中间件获取

    if (!user_id) {
      ctx.status = 401;
      ctx.body = { success: false, message: '请先登录' };
      return;
    }

    if (!property_id || !rating) {
      ctx.status = 400;
      ctx.body = { success: false, message: '房源ID和评分不能为空' };
      return;
    }

    if (rating < 1 || rating > 5) {
      ctx.status = 400;
      ctx.body = { success: false, message: '评分必须在1-5之间' };
      return;
    }

    try {
      const result = await ctx.service.review.create({
        property_id,
        user_id,
        rating,
        content,
        images
      });

      ctx.status = 201;
      ctx.body = { success: true, message: '评价提交成功，等待审核', data: { id: result.insertId } };
    } catch (e) {
      ctx.status = 400;
      ctx.body = { success: false, message: e.message };
    }
  }

  // 更新评价状态（管理员用）
  async updateStatus() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { status } = ctx.request.body;

    if (!['pending', 'approved', 'rejected'].includes(status)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '状态值无效' };
      return;
    }

    try {
      await ctx.service.review.updateStatus(id, status);
      ctx.body = { success: true, message: '状态更新成功' };
    } catch (e) {
      ctx.status = 500;
      ctx.body = { success: false, message: '更新状态失败' };
    }
  }
}

module.exports = ReviewsController;
